<template>
  <div class="phone-management">
    <!-- 搜索|新增 -->
    <div class="set-parameters">
      <el-input
        v-model="version"
        class="device-wechat-id"
        size="small"
        placeholder="请输入版本名"
        clearable
        maxlength="30"
        show-word-limit
      ></el-input>
      <el-input
        v-model="vernumber"
        class="device-wechat-id version-number"
        size="small"
        placeholder="请输入版本号"
        clearable
        maxlength="30"
        show-word-limit
      ></el-input>
      <el-select v-model="flag" size="small" placeholder="是否推送" filterable clearable>
        <el-option v-for="fs in flagStates" :key="fs.id" :label="fs.label" :value="fs.value"></el-option>
      </el-select>
      <el-button type="primary" size="small" @click="queryData">查询</el-button>
      <el-button type="primary" size="small" @click="showDialog">添加</el-button>
    </div>

    <!-- 信息展示 -->
    <el-table :data="tableData" stripe style="width: 100%" height="60px">
      <el-table-column prop="version" label="版本名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="vernumber" label="版本号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="packagename" label="包名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="flag" label="是否推送升级" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-text="scope.row.flag === 0 ? '已推送' : '未推送'"></span>
        </template>
      </el-table-column>
      <el-table-column prop="packageurl" label="软件包地址" header-align="center" align="center">
        <template slot-scope="scope">
          <span :title="scope.row.packageurl" class="message-content" v-text="scope.row.packageurl"></span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" header-align="center" align="center">
        <template slot-scope="scope">
          <span v-text="$options.filters.transformTime2Minute(scope.row.createTime)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          <el-button
            style="background-color: #ff9f00; color: #ffffff"
            type="warning"
            size="mini"
            @click="pushVersionId(scope.row)"
          >
            推送更新
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="pageSize"
      :pager-count="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>

    <el-dialog :modal="false" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form ref="ruleForm" :model="form" :rules="rules">
        <el-form-item label="版本名称" :label-width="formLabelWidth" prop="version">
          <el-input
            v-model="form.version"
            placeholder="请输入版本名称"
            clearable
            maxlength="50"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本号" :label-width="formLabelWidth" prop="vernumber">
          <el-input
            v-model="form.vernumber"
            placeholder="请输入版本号"
            clearable
            maxlength="50"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="APP包名" :label-width="formLabelWidth" prop="packagename">
          <el-input
            v-model="form.packagename"
            placeholder="请输入APP包名"
            clearable
            maxlength="50"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="填写内容" :label-width="formLabelWidth" prop="packageurl">
          <el-input
            v-model="form.packageurl"
            placeholder="请输入url"
            clearable
            maxlength="200"
            show-word-limit
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-upload
          ref="elUpload"
          class="upload-demo"
          drag
          :multiple="false"
          accept=".apk"
          :action="actionUrl"
          :data="upData"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传apk文件，且不超过10M</div>
        </el-upload>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrAddDevice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { queryVersion, deleteVersion, addVersion, updateVersion, pushVersion } from '@/api/httpApiAdmin'

export default {
  name: 'VersionControl',
  data() {
    return {
      tableData: [], // 表格中的数据
      upData: { myfile: '', packageName: 'pc' }, // 上传文件data

      version: '', // 版本
      vernumber: '', // 版本号
      packagename: '', // 包名
      flag: '', // 推送
      flagStates: [
        {
          id: 'flagState0',
          value: 0,
          label: '已推送'
        },
        {
          id: 'flagState1',
          value: 1,
          label: '未推送'
        }
      ], // 推送状态列表

      pageNo: 1, // 第几页
      pageSize: 20, // 每页几个数据
      total: 0, // 总数
      dialogTitle: '添加版本',
      dialogVisible: false, // 显示dialog
      formLabelWidth: '120px',
      form: {
        cid: '', // 必传
        version: '', // 版本名称
        vernumber: '', // 版本号
        packagename: '', // 包名
        packageurl: '' // 安装包url
      }, // 表单
      rules: {
        version: [{ required: true, message: '请输入版本名称', trigger: 'blur' }],
        vernumber: [{ required: true, message: '请输入版本号', trigger: 'blur' }],
        packagename: [{ required: true, message: '请输入app包名', trigger: 'blur' }],
        packageurl: [{ required: true, message: '请输入url', trigger: 'blur' }]
      } // 表单验证
    }
  },
  computed: {
    ...mapState({
      adminInfo: 'adminInfo'
    }),
    ...mapGetters({
      actionUrl: 'actionUrl'
    })
  },
  mounted() {
    this.queryDataSilence()
  },
  methods: {
    // 分页查询数据
    queryData() {
      queryVersion(
        this.adminInfo.cid,
        this.version,
        this.vernumber,
        this.packagename,
        this.flag,
        this.pageNo,
        this.pageSize
      ).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.rows || []
          this.total = res.data.records || 0
          this.$message({
            type: 'success',
            message: '查询成功！',
            duration: 1000
          })
        }
      })
    },
    queryDataSilence() {
      queryVersion(
        this.adminInfo.cid,
        this.version,
        this.vernumber,
        this.packagename,
        this.flag,
        this.pageNo,
        this.pageSize
      ).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data.rows || []
          this.total = res.data.records || 0
        }
      })
    },
    // 修改pageSize
    handleSizeChange(val) {
      if (this.pageSize === val) return
      this.pageSize = val
      this.queryData()
    },
    // 修改当前页
    handleCurrentChange(val) {
      this.pageNo = val
      this.queryData()
    },
    // 显示dialog
    showDialog() {
      this.resetForm()
      this.dialogTitle = '添加版本'
      this.dialogVisible = true
    },
    // 修改或添加设备
    updateOrAddDevice() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { id, version, vernumber, packagename, packageurl } = this.form
          const cid = this.adminInfo.cid
          if (this.dialogTitle === '添加版本') {
            addVersion(cid, version, vernumber, packagename, packageurl).then((res) => {
              if (res.code === 0) {
                this.$refs.elUpload.clearFiles()
                this.queryDataSilence()
                this.dialogVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功!',
                  duration: 1000
                })
              }
            })
          } else {
            updateVersion(id, cid, version, vernumber, packagename, packageurl).then((res) => {
              if (res.code === 0) {
                this.$refs.elUpload.clearFiles()
                this.queryDataSilence()
                this.dialogVisible = false
                this.$message({
                  type: 'success',
                  message: '更新成功',
                  duration: 1000
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm() {
      this.form = {
        cid: '', // 必传
        version: '', // 版本名称
        vernumber: '', // 版本号
        packagename: '', // 包名
        packageurl: '' // 安装包url
      }
    },
    // 显示编辑dialog
    handleEdit(index, row) {
      for (const key in row) {
        if (row.hasOwnProperty(key)) {
          if (key === 'state') {
            this.form[key] = row[key] === 1
          } else {
            this.form[key] = row[key]
          }
        }
      }
      this.dialogTitle = '编辑版本'
      this.dialogVisible = true
    },
    // 显示编辑dialog
    pushVersionId(row) {
      pushVersion(row.id).then((res) => {
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '推送成功',
            duration: 1000
          })
        }
      })
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm('是否删除设备？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteVersion(row.id).then((res) => {
            if (res.code === 0) {
              const pn = Math.ceil((this.total[this.activeName] - 1) / this.pageSize)
              if (this.pageNo > pn) {
                this.pageNo = pn
              }
              this.queryDataSilence()
              this.$message({
                type: 'success',
                message: '删除成功!',
                duration: 1000
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消',
            duration: 1000
          })
        })
    },
    // 文件验证
    beforeUpload(file) {
      const isApk = file.type === 'application/vnd.android.package-archive'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isApk) {
        this.$message.warning('上传视频只能是 MP4 格式!')
      }
      if (!isLt2M) {
        this.$message.warning('上传视频大小不能超过 20MB!')
      }
      if (isApk && isLt2M) {
        this.upData.myfile = file
      }
      return isApk && isLt2M
    },
    // 上传成功
    uploadSuccess(res, file) {
      this.form.version = file.name.replace(/\.apk/, '')
      this.form.packageurl = res.data.url
      // fileList.splice(0, 1)
    },
    // 上传失败
    uploadError(err) {
      this.$alert(err, '文件上传失败', { type: 'error' })
    }
  }
}
</script>

<style lang="scss" scoped>
.phone-management {
  height: 100%;
  display: flex;
  flex-direction: column;

  .set-parameters {
    padding: 10px 5px;
    display: flex;
    align-items: center;
    border-bottom: solid $border-color-1 2px;
    .el-button,
    .version-number,
    .el-select {
      margin-left: 20px;
    }
    ::v-deep .device-wechat-id {
      width: 220px;
      .el-input__inner {
        width: 220px;
      }
    }
  }

  .el-pagination {
    padding: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-top: solid 1px $border-color-1;
    background-color: white;
  }

  ::v-deep .el-dialog {
    width: 500px;
    .el-dialog__body {
      .el-form {
        width: 400px;
        .upload-demo {
          margin-left: 38px;
        }
      }
    }
  }
  ::v-deep .message-content {
    @include ellipsis(1);
  }
}
</style>
